package com.xunyoutest.shop.ui.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chinaums.pppay.unify.UnifyPayListener;
import com.chinaums.pppay.unify.UnifyPayPlugin;
import com.chinaums.pppay.unify.UnifyPayRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.xunyoutest.shop.application.MyApplication;
import com.xunyoutest.shop.base.BasePresenter;
import com.xunyoutest.shop.config.Api;
import com.xunyoutest.shop.config.Constants;
import com.xunyoutest.shop.event.WxEvent;
import com.xunyoutest.shop.ui.view.MainView;
import com.xunyoutest.shop.utils.CommonTools;
import com.xunyoutest.shop.utils.JsonParseUtils;
import com.xunyoutest.shop.utils.PayResult;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xunyoutest.shop.widget.InquiryDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

import static android.app.Activity.RESULT_CANCELED;

/**
 * Created by admin on 2018/9/20.
 */

public class MainPresenter extends BasePresenter<MainView> {
    private Context context;
    private Activity activity;
    private WebView webView;

    private String permId, permKey;
    private String orderId; //记录订单ID
    //微信
    private IWXAPI msgApi;
    //腾讯
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;
    private UnifyPayPlugin payPlugin;
    //极光
    private int sequence = 0X000000; //极光推送操作的序列号
    //ali
    private final int FLAG_AliPay = 0x000;
    private final int CODE_QR_CODE = 0x001;         //扫描二维码requestCode
    private final int CODE_CHOOSER_IMAGE = 0x002;   //选择图片requestCode

    private Handler handler = new Handler();

    private ValueCallback valueCall;
    private ValueCallback<Uri[]> filePathCall;
    private Uri imageUri;

    private boolean isError = false;
    private boolean isRestart = false;

    private LocationClient mLocationClient = null;
    private String addressInfo = "";


    public MainPresenter(MainView mainView, Context context, Activity activity) {
        attachView(mainView);
        this.context = context;
        this.activity = activity;
    }

    public void requestPermissions() {
        RxPermissions rxPermissions = new RxPermissions((FragmentActivity) activity);
        rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            location();
                        } else {
                            baseView.showToast("获取权限被拒绝");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initWebView();
        //设置极光别名
        permId = Constants.getPermId();
        permKey = Constants.getPermKey();
        JPushInterface.setAlias(context, sequence, permId);
        msgApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID);
        //传入参数APPID和全局Context上下文
        mTencent = Tencent.createInstance(Constants.QQ_APP_ID, activity.getApplicationContext());
        payPlugin = UnifyPayPlugin.getInstance(context);
        payPlugin.setListener((resultCode, resultInfo) -> {
            switch (resultCode) {
                case UnifyPayListener.ERR_OK:
                    baseView.showToast("支付成功");
                    baseView.webView().loadUrl(Api.PAY_RETURN + "?isapp=android&order_id=" + orderId);
                    break;
                case UnifyPayListener.ERR_USER_CANCEL:
                    baseView.webView().reload();
                    baseView.showToast("取消支付");
                    break;
                case UnifyPayListener.ERR_PARARM:
                case UnifyPayListener.ERR_SENT_FAILED:
                case UnifyPayListener.ERR_ORDER_DUPLICATE:
                case UnifyPayListener.ERR_PAY_FAIL:
                case UnifyPayListener.ERR_COMM:
                    baseView.webView().reload();
                    baseView.showToast("支付失败");
                    break;
                case UnifyPayListener.ERR_ORDER_PROCESS:
                    break;
            }
        });
    }

    @SuppressLint({"WrongConstant", "SetJavaScriptEnabled"})
    private void initWebView() {
        if (CommonTools.getNetwork(context) == -1) {
            baseView.showError();
        }
        webView = getBaseView().webView();
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAppCacheEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NORMAL);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setBuiltInZoomControls(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSavePassword(true);
        settings.setSaveFormData(true);
        settings.setGeolocationDatabasePath("/data/data/webView/databases/");
        settings.setSupportZoom(true);
        settings.setDatabaseEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setPluginsEnabled(true);
        settings.setBlockNetworkImage(false);//解决图片不显示
        webView.requestFocus();
        webView.setScrollBarStyle(0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.LOAD_NORMAL);
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        } else {
            //5.1以下需要开启软件加速，避免白屏，5.1以上不能开启会影响webView效率
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        webView.loadUrl(Api.WAP_URL + "?isapp=android");
        String urlStr = activity.getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(urlStr)) {
            webView.loadUrl(urlStr);
        }
        webView.addJavascriptInterface(new JsCallAndroid(), "android");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                //拨打电话
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                    return true;
                }
                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            //银联支付
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
                sslErrorHandler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                isError = true;
                //回调失败的相关操作
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isError) {
                    baseView.showError();
                } else {
                    baseView.hideStatueView();
                }
                isError = false;
            }

        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    baseView.dismissLoadingDialog();
                } else {
                    baseView.showLoadingDialog("请等一等啦");
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String s, GeolocationPermissionsCallback geolocationPermissionsCallback) {
                geolocationPermissionsCallback.invoke(s, true, false);
                super.onGeolocationPermissionsShowPrompt(s, geolocationPermissionsCallback);
            }

            @Override
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                //Android  >= 4.1
                valueCall = valueCallback;
                chooserImage();
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                //Android >= 5.0
                filePathCall = filePathCallback;
                chooserImage();
                return true;
            }
        });
    }

    /**
     * Js交互Android方法
     */
    class JsCallAndroid {
        @JavascriptInterface     //登录
        public void login(String perm_id, String perm_key) {
            JPushInterface.setAlias(context, sequence, perm_id);
            permId = perm_id;
            permKey = perm_key;
            Constants.setPermId(perm_id);
            Constants.setPermKey(perm_key);
        }

        @JavascriptInterface     //登出
        public void logout() {
            JPushInterface.deleteAlias(context, sequence);
            Constants.setPermId("");
            Constants.setPermKey("");
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.removeAllCookie();
            CookieSyncManager.getInstance().sync();
            mTencent.logout(context);   //注销QQ登录
        }

        @JavascriptInterface    //创建微信预订单
        public void setWXOrderId(String orderId) {
            createWXOrder(orderId);
        }

        @JavascriptInterface   //获取支付宝预订单
        public void setAliOrderId(String orderId) {
            createAliPayOrder(orderId);
        }


        @JavascriptInterface
        public void share(String title, String describe, String url, String imgUrl) {
            UMWeb web = new UMWeb(url);
            web.setTitle(title);
            web.setDescription(describe);//描述
            web.setThumb(new UMImage(context, imgUrl));
            new ShareAction(activity)
                    .withMedia(web)
                    .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
                            SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                    .setCallback(new UMShareListener() {
                        @Override
                        public void onStart(SHARE_MEDIA platform) {
                        }

                        @Override
                        public void onResult(SHARE_MEDIA platform) {
                            baseView.showToast("分享成功");
                        }

                        @Override
                        public void onError(SHARE_MEDIA platform, Throwable t) {
                            baseView.showToast("分享失败");
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA platform) {
                            baseView.showToast("分享取消");
                        }
                    }).open();
        }

        @JavascriptInterface
        public void qqLogin() {
            mIUiListener = new BaseUiListener();
            mTencent.login(activity, "all", mIUiListener);
        }

        @JavascriptInterface
        public void wxLogin() {
            if (!msgApi.isWXAppInstalled()) {
                baseView.showToast("未安装微信,请先下载");
                return;
            }
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";//应用授权作用域，如获取用户个人信息则填写snsapi_userinfo
            req.state = "wechat_sdk_demo_test";//用于保持请求和回调的状态，授权请求后原样带回给第三方
            // sendReq是第三方app主动发送消息给微信，发送完成之后会切回到第三方app界面。
            msgApi.sendReq(req);
        }

        @JavascriptInterface
        public void scanQRCode() {
            Intent intent = new Intent(activity, CaptureActivity.class);
            activity.startActivityForResult(intent, CODE_QR_CODE);
        }

        @JavascriptInterface
        public void openMap(String location, String title, String content) {
            try {
                // 自定义打点
                Intent intent = new Intent();
                intent.setData(Uri.parse("baidumap://map/marker?location=" + location + "&title=" + title + "&content=" + content + "&traffic=on&src=andr.baidu.openAPIdemo"));
                context.startActivity(intent);
            } catch (Exception e) {
                baseView.showToast("百度地图未安装");
                final InquiryDialog inquiryDialog = new InquiryDialog(context);
                inquiryDialog.setMessage("是否下载百度地图？")
                        .setNoOnclickListener("取消", new InquiryDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inquiryDialog.dismiss();
                            }
                        })
                        .setYesOnclickListener("确定", new InquiryDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://map.baidu.com/zt/client/index/")));
                                inquiryDialog.dismiss();
                            }
                        }).show();
            }
        }

        @JavascriptInterface
        public void pay(int type, String payData, String order_Id) {
            isRestart = true;
            orderId = order_Id;
            /**快捷支付*/
            final int TYPE_POSTON = 0;
            /**微信支付*/
            final int TYPE_WEIXIN = 1;
            /**支付宝支付*/
            final int TYPE_ALIPAY = 2;
            UnifyPayRequest msg = new UnifyPayRequest();
            switch (type) {
                case TYPE_POSTON:
                    msg.payChannel = UnifyPayRequest.CHANNEL_UMSPAY;
                    msg.payData = payData;
                    payPlugin.sendPayRequest(msg);
                    break;
                case TYPE_WEIXIN:
                    msg.payChannel = UnifyPayRequest.CHANNEL_WEIXIN;
                    msg.payData = payData;
                    payPlugin.sendPayRequest(msg);
                    break;
                case TYPE_ALIPAY:
                    msg.payChannel = UnifyPayRequest.CHANNEL_ALIPAY;
                    msg.payData = payData;
                    payPlugin.sendPayRequest(msg);
                    EventBus.getDefault().post(new WxEvent(1, Api.WAP_URL + "tmpl/member/order_list.html"));
                    break;
            }
        }

        @JavascriptInterface    //保存图片
        public void savePicture(String img) {
            Calendar now = new GregorianCalendar();
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
            String fileName = simpleDate.format(now.getTime());//时间命名，可能一秒有多张图片，最简单的方法，时间后面加数字
            try {
                Bitmap bitmap = getImage(img);
                //保存到本地的确定地址
                String localPath = "/" + fileName + ".jpg";
                saveFile(bitmap, localPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public String getLocation() {
            if (addressInfo != null && !addressInfo.isEmpty()) {
                return addressInfo;
            } else {
                return "定位失败";
            }
        }
    }

    public Bitmap getImage(String url) throws Exception {
        Bitmap bitmap = null;
        URL mUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) mUrl.openConnection();
        if (httpURLConnection != null) {
            httpURLConnection.setDoInput(true);
            httpURLConnection.setReadTimeout(8000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
            }
            httpURLConnection.disconnect();
            return bitmap;
        }
        return null;
    }

    public void saveFile(Bitmap bitmap, String localPath) {
        File file;
        //默认个文件保存路径Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        String path = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)
                ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
                + "/Camera" : "/mnt/sdcard";//保存到SD卡
        try {
            file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            File imgFile = new File(file + localPath);
            FileOutputStream out = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            //保存图片后发送广播通知更新数据库
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(imgFile);
            intent.setData(uri);
            activity.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createWXOrder(String orderId) {
        this.orderId = orderId;
        if (!msgApi.isWXAppInstalled()) {
            //提醒用户没有按照微信
            webView.reload();
            baseView.showToast("未安装微信,请先下载");
            return;
        }
        /*baseView.showLoadingDialog();*/
        OkHttpUtils.post()
                .url(Api.PAY_WXPAY)
                .addParams("order_id", orderId)
                .addParams(" trade_type", "APP")
                .addParams("perm_id", permId)
                .addParams(" perm_key", permKey)
                .build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                /*baseView.dismissLoadingDialog();*/
                webView.reload();
                baseView.showToast("获取订单失败，请重试");
            }

            @Override
            public void onResponse(String response, int id) {
                /*baseView.dismissLoadingDialog();*/
                JsonParseUtils instance = JsonParseUtils.getInstance(response);
                if (instance.parseStatus()) {
                    JSONObject data = instance.parseData();
                    JSONObject orderString = data.getJSONObject("orderString");
                    PayReq request = new PayReq();
                    request.appId = orderString.getString("appid");                     //appId
                    request.partnerId = orderString.getString("mch_id");                //商户号
                    request.prepayId = orderString.getString("prepay_id");              //交易号
                    request.packageValue = "Sign=WXPay";                                    //扩展字段
                    request.nonceStr = orderString.getString("nonce_str");              //随机字符串
                    request.timeStamp = String.valueOf(System.currentTimeMillis() / 1000);  //时间戳
                    StringBuilder sb = new StringBuilder();
                    sb.append("appid=");
                    sb.append(Constants.WX_APP_ID);
                    sb.append('&');
                    sb.append("noncestr=");
                    sb.append(request.nonceStr);
                    sb.append('&');
                    sb.append("package=");
                    sb.append(request.packageValue);
                    sb.append('&');
                    sb.append("partnerid=");
                    sb.append(request.partnerId);
                    sb.append('&');
                    sb.append("prepayid=");
                    sb.append(request.prepayId);
                    sb.append('&');
                    sb.append("timestamp=");
                    sb.append(String.valueOf(System.currentTimeMillis() / 1000));
                    sb.append('&');
                    sb.append("key=");
                    sb.append(Constants.WX_API_SECRET);
                    String appSign = CommonTools.encrypt(sb.toString());
                    request.sign = appSign;                        //签名
                    msgApi.sendReq(request);
                } else {
                    webView.reload();
                    baseView.showToast("获取订单失败，请重试");
                }
            }
        });
    }

    public void createAliPayOrder(String orderId) {
        this.orderId = orderId;
        /*baseView.showLoadingDialog();*/
        OkHttpUtils.post().url(Api.PAY_ALIPAY)
                .addParams("order_id", orderId)
                .addParams("perm_id", permId)
                .addParams(" perm_key", permKey)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                /*baseView.dismissLoadingDialog();*/
                webView.reload();
                baseView.showToast("获取订单失败，请重试");
            }

            @Override
            public void onResponse(String response, int id) {
                baseView.dismissLoadingDialog();
                JsonParseUtils instance = JsonParseUtils.getInstance(response);
                if (instance.parseStatus()) {
                    JSONObject data = instance.parseData();
                    final String orderInfo = data.getString("orderString");
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask aliPay = new PayTask(activity);
                            Map<String, String> result = aliPay.payV2(orderInfo, true);
                            Message msg = new Message();
                            msg.what = FLAG_AliPay;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } else {
                    webView.reload();
                    baseView.showToast("获取订单失败，请重试");
                }
            }
        });
    }

    /**
     * webView选择图片
     */
    private void chooserImage() {
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(file);

        final List<Intent> cameraIntents = new ArrayList<>();
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = context.getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);
        }
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        Intent chooserIntent = Intent.createChooser(intent, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        activity.startActivityForResult(chooserIntent, CODE_CHOOSER_IMAGE);
    }

    /**
     * 自定义监听器实现IUiListener
     */
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            JSONObject obj = JSONObject.parseObject(response.toString());
            final String openID = obj.getString("openid");
            final String accessToken = obj.getString("access_token");
            String expires = obj.getString("expires_in");
            qq_Login(accessToken, openID, expires);
        }

        @Override
        public void onError(UiError uiError) {
            baseView.showToast("授权失败");
        }

        @Override
        public void onCancel() {
            baseView.showToast("授权取消");
        }
    }

    private void qq_Login(final String accessToken, final String openID, final String expires) {
        OkHttpUtils.post().url("https://graph.qq.com/oauth2.0/me?")
                .addParams("access_token", accessToken)
                .addParams("unionid", "1")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                baseView.showToast("登录失败");
            }

            @Override
            public void onResponse(String response, int id) {
                String str = response.subSequence(response.indexOf("{"), response.lastIndexOf("}") + 1).toString();
                JsonParseUtils instance = JsonParseUtils.getInstance(str);
                final String unionid = instance.getObject().getString("unionid");
                if (unionid != null && !"".equals(unionid)) {
                    Log.i(unionid + "unionid", unionid);
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                    QQToken qqToken = mTencent.getQQToken();
                    mUserInfo = new UserInfo(context, qqToken);
                    mUserInfo.getUserInfo(new IUiListener() {
                        @Override
                        public void onComplete(Object response) {
                            JSONObject userObj = JSONObject.parseObject(response.toString());
                            String nickname = userObj.getString("nickname");
                            String headImgUrl = userObj.getString("figureurl_qq_2");
                            String sex = userObj.getString("gender");
                            loginToOur(unionid, openID, accessToken, headImgUrl, nickname, sex);
                        }

                        @Override
                        public void onError(UiError uiError) {
                            baseView.showToast("登录失败");
                            webView.goBack();
                        }

                        @Override
                        public void onCancel() {
                            baseView.showToast("登录取消");
                            webView.goBack();
                        }
                    });
                } else {
                    String error = instance.getObject().getString("error");
                    String error_description = instance.getObject().getString("error_description");
                    baseView.showToast("登录失败" + error_description);
                    webView.goBack();
                }
            }
        });
    }

    private void loginToOur(String unionId, String openid, String access_token, String headImgUrl, String nickname, String sex) {
        OkHttpUtils.post().url(Api.AUTH_LOGIN)
                .addParams("bind_id", unionId)
                .addParams("access_token", access_token)
                .addParams("openid", openid)
                .addParams("bind_avator", headImgUrl)
                .addParams("bind_nickname", nickname)
                .addParams("bind_gender", sex)
                .addParams("type", "qq")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                baseView.showToast("登录失败");
            }

            @Override
            public void onResponse(String response, int id) {
                JsonParseUtils instance = JsonParseUtils.getInstance(response);
                if (instance.parseStatus()) {
                    JSONObject data = instance.parseData();
                    String url = URLDecoder.decode(data.getString("url"));
                    webView.loadUrl(url);
                } else {
                    baseView.showToast("登录失败");
                }
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        UMShareAPI.get(context).onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_CHOOSER_IMAGE:
                if (valueCall == null && filePathCall == null) {
                    return;
                }
                if (resultCode == activity.RESULT_OK) {
                    if (data != null) {
                        Uri result = data.getData();
                        if (valueCall != null) {
                            valueCall.onReceiveValue(result);
                            valueCall = null;
                        } else if (filePathCall != null) {
                            Uri[] results = null;
                            String dataString = data.getDataString();
                            ClipData clipData = data.getClipData();
                            if (clipData != null) {
                                results = new Uri[clipData.getItemCount()];
                                for (int i = 0; i < clipData.getItemCount(); i++) {
                                    ClipData.Item item = clipData.getItemAt(i);
                                    results[i] = item.getUri();
                                }
                            }
                            if (dataString != null) {
                                results = new Uri[]{Uri.parse(dataString)};
                            }
                            filePathCall.onReceiveValue(results);
                            filePathCall = null;
                        }
                    }else{
                        Uri[] us = new Uri[]{imageUri};
                        filePathCall.onReceiveValue(us);
                        filePathCall = null;
                    }
                } else if (resultCode == RESULT_CANCELED) {
                    filePathCall.onReceiveValue(null);
                    filePathCall = null;
                }
                break;
            case com.tencent.connect.common.Constants.REQUEST_LOGIN:
                //QQ登录成功返回来的结果
                Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
                break;
            case CODE_QR_CODE:
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String result = bundle.getString(CodeUtils.RESULT_STRING);
                        webView.loadUrl("javascript:getAppQrcode(" + result + ")");
                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        baseView.showToast("解析二维码失败");
                    }
                }
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWxEvent(WxEvent event) {
        int type = event.getType();
        if (type == 1) {
            //微信登录
            String url = event.getUrl();
            webView.loadUrl(url);
        } else {
            //微信支付
            int errCode = event.getErrCode();
            if (errCode == 0) {
                baseView.showToast("支付成功");
                baseView.webView().loadUrl(Api.PAY_RETURN + "?isapp=android&order_id=" + orderId);
            } else if (errCode == -1) {
                baseView.webView().reload();
                baseView.showToast("支付失败");
            } else {
                baseView.webView().reload();
                baseView.showToast("支付取消");
            }
        }
    }

    class Handler extends android.os.Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FLAG_AliPay:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    switch (resultStatus) {
                        case "9000":
                            baseView.showToast("支付成功");
                            baseView.webView().loadUrl(Api.PAY_RETURN + "?isapp=android&order_id=" + orderId);
                            break;
                        case "4000":
                            webView.reload();
                            baseView.showToast("支付失败");
                            break;
                        case "6001":
                            webView.reload();
                            baseView.showToast("取消支付");
                            break;
                        default:
                            webView.reload();
                            baseView.showToast("取消支付");
                            break;
                    }
                    break;
            }
        }
    }

    private void location() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        option.setScanSpan(180000);//3分钟自动定位一次
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll");
        option.setOpenGps(true);
        option.setLocationNotify(false);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(true);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient = new LocationClient(context);
        mLocationClient.setLocOption(option);
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                //当前定位城市
                String address = bdLocation.getAddrStr();
                String province = bdLocation.getProvince();
                String city = bdLocation.getCity();
                String district = bdLocation.getDistrict();
                String street = bdLocation.getStreet();
                String streetNumber = bdLocation.getStreetNumber();
                String longitude = String.valueOf(bdLocation.getLongitude());
                String latitude = String.valueOf(bdLocation.getLatitude());
                addressInfo = longitude + "," + latitude;
            }
        });
        mLocationClient.start();
    }

    public void onRestart() {
        if (isRestart) {
            webView.reload();
        }
        isRestart = false;
    }

    public void onDestroy() {
        EventBus.getDefault().unregister(this);
    }
}

